package part18;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.TreeSet;

/**
 * @author wcj
 * @Date 2021/6/3 18:06
 * @Version 1.0
 */
public class Part1814 {

    public static void main(String[] args) {
        String file = TextFile.read("./src/part18/Part1814.java");
        TextFile.write("./src/part18/test.txt", file);
        TextFile text = new TextFile("./src/part18/test.txt");
        text.write("test2.txt");
        TreeSet<String> words = new TreeSet<>(new TextFile("./src/part18/Part1814.java", "\\W+"));
        System.out.println(words.headSet("a"));
    }
}

/**
 * 文件读写的工具类，提供读写方法，并且将其内容写入到ArrayList张方便我们操作
 */
class TextFile extends ArrayList<String> {

    /**
     * 从特定的文件读取信息
     *
     * @param filename
     * @return
     */
    public static String read(String filename) {
        StringBuilder sb = new StringBuilder();
        try {
            BufferedReader in = new BufferedReader(new StringReader(new File(filename).getAbsolutePath()));
            try {
                String s;
                while ((s = in.readLine()) != null) {
                    sb.append(s);
                    sb.append("\n");
                }
            } finally {
                in.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return sb.toString();
    }

    /**
     * 文件的写操作
     *
     * @param filename
     * @param text
     */
    public static void write(String filename, String text) {
        try {
            PrintWriter out = new PrintWriter(new File(filename).getAbsoluteFile());
            try {
                out.print(text);
            } finally {
                out.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public TextFile(String filename, String splitter) {
        super(Arrays.asList(read(filename).split(splitter)));
        if (this.get(0).equals(" ")) {
            this.remove(0);
        }
    }

    public TextFile(String filename) {
        this(filename, "\n");
    }

    public void write(String filename) {
        try {
            PrintWriter out = new PrintWriter(new File(filename).getAbsoluteFile());
            try {
                for (String s : this) {
                    out.write(s);
                }
            } finally {
                out.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
